package com.hzjq.encrypt

import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.alibaba.fastjson.JSONObject
import com.hzjq.encrypt.bean.EnBean
import com.hzjq.encrypt.bean.Lg
import com.hzjq.encrypt.bean.Lgs
import com.hzjq.encrypt.encrypt.EncryptUtils
import com.hzjq.encrypt.pop.SqrqPop
import com.hzjq.encrypt.ui.*
import com.hzjq.encrypt.util.EToast
import com.hzjq.encrypt.util.FileStreamX
import com.hzjq.encrypt.util.KeyBoradX
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.util.PermissionConstants
import com.lxj.xpopup.util.XPermission
import com.sky.filepicker.upload.Constants
import com.sky.filepicker.upload.LocalUpdateActivity
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.layout_en_info.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File
import java.io.FileInputStream


class MainActivity : AppCompatActivity() {

    private var encrypt: EnBean? = null

    private var path = ""

    private lateinit var outFilePath: String

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)

        EventBus.getDefault().register(this)

        EToast.init(this)

//        if (hasPermission()) {
//            onGetPermissionsSuccess()
//        } else {
            reqPermissions()
//        }

        onUseBatchPwd()
    }


    private fun onUseBatchPwd(){
        batchPwdBox.setOnCheckedChangeListener { buttonView, isChecked ->
            if(isChecked){
                encryptFileLayout.visibility = View.GONE
                encryptBatchFileLayout.visibility = View.VISIBLE
            } else {
                encryptFileLayout.visibility = View.VISIBLE
                encryptBatchFileLayout.visibility = View.GONE
            }
        }
    }


    private fun onGetPermissionsSuccess() {
        outFilePath = FileStreamX.getOutDir(this)

        encryptOutFilePath.text = "输出路径:$outFilePath"

        encryptFileBtn.setOnClickListener {
            val intent = Intent(this, LocalUpdateActivity::class.java)
            intent.putExtra("maxNum", 1)//设置最大选择数
            startActivityForResult(intent, 123)
        }

        //523247
        encryptWriteFileBtn.setOnClickListener {
            if (TextUtils.isEmpty(path)) {
                EToast.toast("请选择解密文件")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(encryptFileKeyEt.text) || encryptFileKeyEt.text.toString().length != 6) {
                EToast.toast("请输入正确的解密密码")
                return@setOnClickListener
            }

            encrypt()
        }


        encryptBatchFileBtn.setOnClickListener {
            val intent = Intent(this, LocalUpdateActivity::class.java)
            intent.putExtra("maxNum", 1)//设置最大选择数
            startActivityForResult(intent, 123)
        }

        encryptReadBatchFileBtn.setOnClickListener {
            if (TextUtils.isEmpty(path)) {
                EToast.toast("请选择批量密码文件")
                return@setOnClickListener
            }
            if(TextUtils.isEmpty(encryptBatchFileYXQEt.text)){
                EToast.toast("请输入量密码有效期")
                return@setOnClickListener
            }
            encrypt()
        }

        encryptOutFileBtn.setOnClickListener {
            encode()
        }

        onlineAuthLayout.setOnClickListener {
            OffAuthFileActivity.start(this,0)
        }

        offAuthLayout.setOnClickListener {
            XtmAuthFileActivity.start(this)
        }

        gzmAuthLayout.setOnClickListener {
            GzmActivity.start(this)
        }

        setOnEncryptItemClick()
    }

    private fun reqPermissions() {
        XPermission.create(this, PermissionConstants.STORAGE)
            .callback(object:XPermission.SimpleCallback{
                override fun onGranted() {
                    onGetPermissionsSuccess()
                }

                override fun onDenied() {
                    EToast.toast("权限申请失败")
                }

            }).request()
    }


    private fun hasPermission(): Boolean {
        return ContextCompat.checkSelfPermission(
            this,
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE
        ) !== PackageManager.PERMISSION_GRANTED
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            123 -> if (resultCode == Constants.UPLOAD_FILE_RESULT && data != null) {
                path = data.getStringArrayListExtra("pathList")?.get(0) ?: ""
                encryptFileBtn.text = path
                encryptBatchFileBtn.text = path
            }
        }
    }


    @SuppressLint("CheckResult")
    private fun encrypt() {
        showEmptyEncrypt()
        hideKeyBord()
        val load = XPopup.Builder(this)
            .asLoading("正在解密...")
            .show()
        Observable.create<String> {
            it.onNext(FileStreamX.read(FileInputStream(path)))
        }.subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnError {
                load.dismiss()
                EToast.toast("解密失败，请检查解密文件或密码是否正确")
            }
            .subscribe {
                load.dismiss()
                if(encryptBatchFileLayout.isShown){
                    encryptBatchPwdFile(it)
                } else {
                    val enCode = EncryptUtils.decodeNoURL(
                        it,
                        EncryptUtils.DE_KEY_BASE + encryptFileKeyEt.text.toString()
                    )
                    if (TextUtils.isEmpty(enCode)) {
                        showEmptyEncrypt()
                    } else {
                        val encryptBean = JSONObject.parseObject(enCode, EnBean::class.java)
                        if (encryptBean != null) {
                            showEncrypt(encryptBean)
                        }
                    }
                }
            }
    }



    private fun encryptBatchPwdFile(it:String){
        Log.e("text",it)
        if(it.isNullOrEmpty()){
            showEmptyEncrypt()
        } else {
            val split = it.trim().split("\n")
            val encrypt = EnBean()
            encrypt.lgs = Lgs()
            encrypt.lgs.lg = arrayListOf()
            val date = encryptBatchFileYXQEt.text.toString()
            split.forEach { s->
                val param = s.split(",")
                if(!TextUtils.equals("UID",param[0])) {
                    val lg = Lg()
                    lg.gzm = param[1].replace("'","")
                    lg.uid = param[0].replace("'","")
                    lg.yxq = date
                    lg.fbh = lg.uid
                    lg.gzmcwxx = "0"
                    encrypt.lgs.lg.add(lg)
                }
            }
            showEncrypt(encrypt)
        }
    }


    private fun showEncrypt(encrypt: EnBean) {
        this.encrypt = encrypt
        encrypt.lgs?.let { encryptLg.text = it.lg.size.toString() + "发" }
        encrypt.jbqys?.let { encryptJb.text = it.jbqy.size.toString() + "个区域" }
        encrypt.zbqys?.let { encryptZb.text = it.zbqy.size.toString() + "个区域" }
        encrypt.sbbhs?.let { encryptQbq.text = it.size.toString() + "台起爆器" }
        encryptSqrq.text = encrypt.sqrq
    }

    private fun showEmptyEncrypt() {
        this.encrypt = null
        encryptLg.text = "0发"
        encryptJb.text = "0个区域"
        encryptZb.text = "0个区域"
        encryptQbq.text = "0台起爆器"
        encryptSqrq.text = ""
    }


    private fun setOnEncryptItemClick() {
        encryptLg.setOnClickListener {
            hideKeyBord()
            LgEditorActivity.start(this, encrypt)
        }
        encryptJb.setOnClickListener {
            hideKeyBord()
            JbqyActivity.start(this, encrypt)
        }
        encryptZb.setOnClickListener {
            hideKeyBord()
            ZbqyActivity.start(this, encrypt)
        }
        encryptQbq.setOnClickListener {
            hideKeyBord()
            QbqActivity.start(this, encrypt)
        }
        encryptSqrq.setOnClickListener {
            hideKeyBord()
            SqrqPop.show(this, object : SqrqPop.OnSqrqEditorCallback {
                override fun onSqrqEditor(time: String) {
                    if (encrypt == null) {
                        encrypt = EnBean()
                    }
                    encrypt?.sqrq = time
                    if (encrypt != null) {
                        showEncrypt(encrypt!!)
                    }
                }
            }, if (encrypt == null) "" else encrypt!!.sqrq)
        }

    }


    @SuppressLint("CheckResult")
    private fun encode() {
        hideKeyBord()
        if (encrypt == null) {
            EToast.toast("没有加密信息")
            return
        }
        if (TextUtils.isEmpty(encryptOutFileKeyEt.text) || encryptOutFileKeyEt.text.length != 6) {
            EToast.toast("请输入正确的加密密码")
            return
        }
        if (TextUtils.isEmpty(encryptOutFileNameEt.text)) {
            EToast.toast("请输入加密输出文件名")
            return
        }

        val load = XPopup.Builder(this)
            .asLoading("正在加密...")
            .show()
        Observable.create<Boolean> {
            val endocde =
                EncryptUtils.endocdeNoURL(
                    JSONObject.toJSONString(encrypt),
                    EncryptUtils.DE_KEY_BASE + encryptOutFileKeyEt.text
                )
            val write = FileStreamX.write(
                endocde, outFilePath
                        + File.separator.toString()
                        + if (encryptOutFileNameEt.text.toString().endsWith(".txt"))
                    encryptOutFileNameEt.text.toString() else
                    encryptOutFileNameEt.text.toString() + ".txt"
            )
            //73173842099825
            FileStreamX.refresh(this)
            it.onNext(write)
        }.subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnError {
                load.dismiss()
                EToast.toast("加密失败")
            }
            .subscribe {
                load.dismiss()
                EToast.toast(if (it) "加密成功" else "加密失败")
            }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEnBean(en: EnBean) {
        this.encrypt = en
        if(!TextUtils.isEmpty(en.filePath)){
            if(TextUtils.equals("no path",en.filePath)){
                encryptFileBtn.text = ""
                encryptFileKeyEt.setText("")
            } else {
                encryptFileBtn.text = en.filePath
                encryptFileKeyEt.setText(en.code)
            }
        }
        showEncrypt(en)
    }

    private fun hideKeyBord() {
        KeyBoradX.hideKeyBoard(encryptFileKeyEt)
        KeyBoradX.hideKeyBoard(encryptOutFileKeyEt)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }


}